<?php
/**
 * Created by PhpStorm.
 * User: liball
 * Date: 2015-07-07
 * Time: 14:41
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{

    public function index()
    {
        $categories = Category::latest()->paginate(20);
        return view('admin.categories.index', compact('categories'));
    }


    public function edit($id)
    {
        $category = Category::findOrNew($id);
        return view('admin.categories.edit', compact('category'));
    }

    public function update($id, Request $request)
    {
        $category = Category::find($id);
        $data = $request->except('_token');
        if (!isset($data['banner'])) {
            $data['banner'] = false;
        }
        if (!isset($data['top'])) {
            $data['top'] = false;
        }
        $category->update($data);
        return redirect()->to('admin/categories');
    }

    public function create()
    {
        return view('admin.categories.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, Category::$rules);
        $data = $request->except('_token');
        if (!$request->has('top')) {
            $data['top'] = false;
        }
        if (!$request->has('banner')) {
            $data['banner'] = false;
        }
        Category::create($request->all());
        return redirect()->to('admin/categories');
    }

    public function process(Request $request)
    {
        $action = $request->get('action');
        $ids = $request->get('ids');
        if ($action == 'delete') {
            foreach ($ids as $id) {
                Category::destroy($id);
            }
        }
        return redirect()->back();

    }
}